package org.etlt.op.ud;

import org.etlt.expression.VariableContext;
import org.etlt.expression.function.FunctionActor;
import org.etlt.expression.function.FunctionEnabled;
import org.etlt.job.JobContext;

@FunctionEnabled(value = "mapping2", help = "if mapped value is null, return null")
public class Mapping2 implements FunctionActor {

    @Override
    public Object operate(VariableContext context, Object... args) {
        checkArgs(args);
        String catalog = args[0].toString();
        if (args[1] == null) {
            return args.length > 2 ? args[2] : null;
        }
        String key = args[1].toString();
        Object mappedValue = ((JobContext) context).mapping(catalog, key);
        if (mappedValue != null)
            return mappedValue;
        return (mappedValue == null && args.length > 2) ?
                args[2] :
                null;
    }

    @Override
    public void checkArgs(Object... args) {
        if (args.length < 2) {
            throw new IllegalArgumentException("mapping function need 2 argument at least: mapping catalog , mapping key and possible default value");
        }
    }
}
